package com.qst.controller;

import com.qst.pojo.entity.Order;
import com.qst.pojo.entity.User;
import com.qst.pojo.entity.UserNotificationSettings;
import com.qst.repository.OrderRepository;
import com.qst.repository.UserRepository;
import com.qst.repository.UserNotificationSettingsRepository;
import com.qst.util.JwtUtil;
import com.qst.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private UserNotificationSettingsRepository notificationSettingsRepository;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取用户列表（分页）
     */
    @GetMapping
    public Result<Map<String, Object>> getUserList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String role
    ) {
        try {
            // 创建分页对象（页码从0开始）
            Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "id"));

            // 处理空字符串为null
            String usernameFilter = (username != null && username.trim().isEmpty()) ? null : username;
            User.UserRole roleFilter = null;
            if (role != null && !role.trim().isEmpty()) {
                try {
                    roleFilter = User.UserRole.valueOf(role);
                } catch (IllegalArgumentException e) {
                    logger.warn("无效的角色值: {}", role);
                }
            }

            // 根据条件查询用户列表
            Page<User> userPage = userRepository.findByConditions(usernameFilter, roleFilter, pageable);

            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("list", userPage.getContent());
            data.put("total", userPage.getTotalElements());
            data.put("page", page);
            data.put("pageSize", pageSize);

            return Result.success(data);
        } catch (Exception e) {
            logger.error("获取用户列表失败", e);
            return Result.error("获取用户列表失败");
        }
    }

    /**
     * 获取单个用户
     */
    @GetMapping("/{id}")
    public Result<User> getUser(@PathVariable Integer id) {
        try {
            Optional<User> user = userRepository.findById(id);
            if (user.isPresent()) {
                return Result.success(user.get());
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            logger.error("获取用户失败", e);
            return Result.error("获取用户失败");
        }
    }

    /**
     * 创建用户
     */
    @PostMapping
    public Result<User> createUser(@RequestBody User user) {
        try {
            // 检查用户名是否已存在
            if (userRepository.findByUsername(user.getUsername()).isPresent()) {
                return Result.error("用户名已存在");
            }

            // 保存用户
            User savedUser = userRepository.save(user);
            return Result.success("用户创建成功", savedUser);
        } catch (Exception e) {
            logger.error("创建用户失败", e);
            return Result.error("创建用户失败");
        }
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public Result<User> updateUser(@PathVariable Integer id, @RequestBody User user) {
        try {
            Optional<User> existingUser = userRepository.findById(id);
            if (existingUser.isEmpty()) {
                return Result.error("用户不存在");
            }

            User userToUpdate = existingUser.get();
            userToUpdate.setRealName(user.getRealName());
            userToUpdate.setPhone(user.getPhone());
            userToUpdate.setEmail(user.getEmail());
            userToUpdate.setAddress(user.getAddress());
            userToUpdate.setRole(user.getRole());
            userToUpdate.setStatus(user.getStatus());

            User updatedUser = userRepository.save(userToUpdate);
            return Result.success("用户更新成功", updatedUser);
        } catch (Exception e) {
            logger.error("更新用户失败", e);
            return Result.error("更新用户失败");
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteUser(@PathVariable Integer id) {
        try {
            if (!userRepository.existsById(id)) {
                return Result.error("用户不存在");
            }

            userRepository.deleteById(id);
            return Result.success("用户删除成功", "删除成功");
        } catch (Exception e) {
            logger.error("删除用户失败", e);
            return Result.error("删除用户失败");
        }
    }

    /**
     * 切换用户状态
     */
    @PutMapping("/{id}/toggle-status")
    public Result<User> toggleUserStatus(@PathVariable Integer id) {
        try {
            Optional<User> existingUser = userRepository.findById(id);
            if (existingUser.isEmpty()) {
                return Result.error("用户不存在");
            }

            User user = existingUser.get();
            user.setStatus(user.getStatus() == User.UserStatus.active ?
                    User.UserStatus.inactive : User.UserStatus.active);

            User updatedUser = userRepository.save(user);
            return Result.success("状态切换成功", updatedUser);
        } catch (Exception e) {
            logger.error("切换用户状态失败", e);
            return Result.error("切换状态失败");
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public Result<User> getCurrentUser(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            if (token == null || token.trim().isEmpty()) {
                return Result.error("未登录或登录已过期");
            }
            
            String jwtToken = token.replace("Bearer ", "").trim();
            Integer userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                return Result.error("无法获取用户信息");
            }
            
            Optional<User> user = userRepository.findById(userId);
            if (user.isPresent()) {
                return Result.success(user.get());
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            logger.error("获取当前用户信息失败", e);
            return Result.error("获取用户信息失败");
        }
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    public Result<String> changePassword(
            @RequestHeader(value = "Authorization", required = false) String token,
            @RequestBody Map<String, String> passwordData) {
        try {
            if (token == null || token.trim().isEmpty()) {
                return Result.error("未登录或登录已过期");
            }
            
            String jwtToken = token.replace("Bearer ", "").trim();
            Integer userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                return Result.error("无法获取用户信息");
            }
            
            String currentPassword = passwordData.get("currentPassword");
            String newPassword = passwordData.get("newPassword");
            
            if (currentPassword == null || currentPassword.trim().isEmpty()) {
                return Result.error("请输入当前密码");
            }
            
            if (newPassword == null || newPassword.trim().isEmpty()) {
                return Result.error("请输入新密码");
            }
            
            Optional<User> userOpt = userRepository.findById(userId);
            if (userOpt.isEmpty()) {
                return Result.error("用户不存在");
            }
            
            User user = userOpt.get();
            
            // 验证当前密码
            if (!user.getPassword().equals(currentPassword)) {
                return Result.error("当前密码不正确");
            }
            
            // 更新密码
            user.setPassword(newPassword);
            userRepository.save(user);
            
            return Result.success("密码修改成功");
        } catch (Exception e) {
            logger.error("修改密码失败", e);
            return Result.error("修改密码失败");
        }
    }
    
    /**
     * 获取当前用户统计数据
     */
    @GetMapping("/me/stats")
    public Result<Map<String, Object>> getCurrentUserStats(
            @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            if (token == null || token.trim().isEmpty()) {
                return Result.error("未登录或登录已过期");
            }
            
            String jwtToken = token.replace("Bearer ", "").trim();
            Integer userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                return Result.error("无法获取用户信息");
            }
            
            // 获取用户所有订单
            List<Order> allOrders = orderRepository.findByCustomerId(userId);
            
            // 计算统计数据
            int totalOrders = allOrders.size();
            
            // 计算总收益（只计算已完成的订单）
            BigDecimal totalEarnings = allOrders.stream()
                    .filter(order -> order.getStatus() == Order.OrderStatus.completed)
                    .map(Order::getTotalAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            // 计算总重量（只计算已完成的订单）
            BigDecimal totalWeight = allOrders.stream()
                    .filter(order -> order.getStatus() == Order.OrderStatus.completed)
                    .map(Order::getTotalWeight)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            // 环保积分（假设 1kg = 10 积分）
            int ecoPoints = totalWeight.multiply(new BigDecimal("10")).intValue();
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalOrders", totalOrders);
            stats.put("totalEarnings", totalEarnings);
            stats.put("totalWeight", totalWeight);
            stats.put("ecoPoints", ecoPoints);
            
            return Result.success(stats);
        } catch (Exception e) {
            logger.error("获取用户统计数据失败", e);
            return Result.error("获取统计数据失败");
        }
    }
    
    /**
     * 获取当前用户的通知设置
     */
    @GetMapping("/me/notification-settings")
    public Result<Map<String, Boolean>> getNotificationSettings(
            @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            if (token == null || token.trim().isEmpty()) {
                return Result.error("未登录或登录已过期");
            }
            
            String jwtToken = token.replace("Bearer ", "").trim();
            Integer userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                return Result.error("无法获取用户信息");
            }
            
            // 查找用户的通知设置，如果不存在则创建默认设置
            UserNotificationSettings settings = notificationSettingsRepository.findByUserId(userId)
                    .orElseGet(() -> {
                        UserNotificationSettings newSettings = new UserNotificationSettings();
                        newSettings.setUserId(userId);
                        newSettings.setNotifyOrderStatus(true);
                        newSettings.setNotifyPriceChange(false);
                        newSettings.setNotifySystemMessage(true);
                        newSettings.setNotifyEmail(true);
                        return notificationSettingsRepository.save(newSettings);
                    });
            
            Map<String, Boolean> result = new HashMap<>();
            result.put("orderStatus", settings.getNotifyOrderStatus());
            result.put("priceChange", settings.getNotifyPriceChange());
            result.put("systemMessage", settings.getNotifySystemMessage());
            result.put("emailNotification", settings.getNotifyEmail());
            
            return Result.success(result);
        } catch (Exception e) {
            logger.error("获取通知设置失败", e);
            return Result.error("获取通知设置失败");
        }
    }
    
    /**
     * 更新当前用户的通知设置
     */
    @PutMapping("/me/notification-settings")
    public Result<String> updateNotificationSettings(
            @RequestHeader(value = "Authorization", required = false) String token,
            @RequestBody Map<String, Boolean> settingsData) {
        try {
            if (token == null || token.trim().isEmpty()) {
                return Result.error("未登录或登录已过期");
            }
            
            String jwtToken = token.replace("Bearer ", "").trim();
            Integer userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                return Result.error("无法获取用户信息");
            }
            
            // 查找或创建通知设置
            UserNotificationSettings settings = notificationSettingsRepository.findByUserId(userId)
                    .orElseGet(() -> {
                        UserNotificationSettings newSettings = new UserNotificationSettings();
                        newSettings.setUserId(userId);
                        return newSettings;
                    });
            
            // 更新设置
            if (settingsData.containsKey("orderStatus")) {
                settings.setNotifyOrderStatus(settingsData.get("orderStatus"));
            }
            if (settingsData.containsKey("priceChange")) {
                settings.setNotifyPriceChange(settingsData.get("priceChange"));
            }
            if (settingsData.containsKey("systemMessage")) {
                settings.setNotifySystemMessage(settingsData.get("systemMessage"));
            }
            if (settingsData.containsKey("emailNotification")) {
                settings.setNotifyEmail(settingsData.get("emailNotification"));
            }
            
            notificationSettingsRepository.save(settings);
            
            return Result.success("通知设置更新成功");
        } catch (Exception e) {
            logger.error("更新通知设置失败", e);
            return Result.error("更新通知设置失败");
        }
    }
}

